<!DOCTYPE html>
<html>

<head>
    <meta charset="utf-8">
    <title></title>
    <meta name="renderer" content="webkit">
    <meta http-equiv="X-UA-Compatible" content="IE=edge,chrome=1">
    <meta name="viewport"
          content="width=device-width, initial-scale=1.0, minimum-scale=1.0, maximum-scale=1.0, user-scalable=0">
    <link rel="stylesheet" href="/layui/css/layui.css" media="all">
    <link rel="stylesheet" href="/style/admin.css" media="all">
</head>

<body>

<div class="layui-fluid">
    <div class="layui-row layui-col-space15">
        <div class="layui-col-md12">
            <div class="layui-card">
                <div class="layui-card-header">人员设置</div>
                <div class="layui-card-body">
                    <div style="margin-bottom: 10px;">
                        <div class="layui-input-item" style="float:left;padding-right:10px;">
                            <form class="layui-form">
                                <div class="layui-inline">
                                    <select id="search-role" lay-search>
                                        <option value="">请选择角色</option>
                                    </select>
                                </div>
                                <div class="layui-inline">
                                    <input id="search-keyword" type="text" placeholder="请输入姓名/账号/手机号"
                                           class="layui-input layui-input-search">
                                </div>
                                <div class="layui-inline">
                                    <a id="btn-search" class="layui-btn">查找</a>
                                </div>
                            </form>
                        </div>
                        <div style="float:right;">
                            <a id="btn-add" class="layui-btn">添加</a>
                            <a id="btn-import" class="layui-btn layui-btn-primary">导入</a>
                            <a id="btn-export" class="layui-btn layui-btn-primary">导出</a>
                            <a id="btn-batch-sync" class="layui-btn layui-btn-primary">同步</a>
                            <a id="btn-batch-delete" class="layui-btn layui-btn-danger">删除</a>
                            <a id="btn-refresh" class="layui-btn layui-btn-primary">刷新</a>
                        </div>
                        <div style="clear:both;"></div>
                    </div>
                    <table class="layui-hide" id="user-table" lay-filter="user-table"></table>
                    <script type="text/html" id="toolbar-operation">
                        <a class="layui-btn layui-btn-xs" lay-event="edit">详情</a>
                        <a class="layui-btn layui-btn-danger layui-btn-xs" lay-event="del">删除</a>
                        <a class="layui-btn layui-btn-primary layui-btn-xs" lay-event="reset">重置密码</a>
                        <a class="layui-btn layui-btn-primary layui-btn-xs" lay-event="qrcode">二维码</a>
                        <a class="layui-btn layui-btn-primary layui-btn-xs" lay-event="sync">同步企微</a>
                    </script>
                </div>
            </div>
        </div>
    </div>
</div>
<script type="text/html" id="user-form">
    <div class="layui-card">
        <div class="layui-card-header">用户详情</div>
        <div class="layui-card-body">
            <form class="layui-form" action="#" lay-filter="user-form">
                <input type="hidden" name="id">
                <div class="layui-form-item">
                    <label class="layui-form-label">姓名</label>
                    <div class="layui-input-block">
                        <input id="name" type="text" name="name" class="layui-input" lay-verify="required">
                    </div>
                </div>
                <div class="layui-form-item">
                    <label class="layui-form-label">账号</label>
                    <div class="layui-input-block">
                        <input id="account" type="text" name="account" class="layui-input" lay-verify="required">
                    </div>
                </div>
                <div class="layui-form-item">
                    <label class="layui-form-label">手机号</label>
                    <div class="layui-input-block">
                        <input type="text" name="mobile" class="layui-input" lay-verify="required|phone">
                    </div>
                </div>
                <div class="layui-form-item">
                    <label class="layui-form-label">性别</label>
                    <input type="radio" name="gender" value="男" title="男" checked>
                    <input type="radio" name="gender" value="女" title="女">
                </div>
                <div class="layui-form-item">
                    <label class="layui-form-label">学历</label>
                    <div class="layui-input-block">
                        <select id="select-xueli" name="education" lay-filter="type" lay-verify="required">
                            <option>选择学历</option>
                            <option value="小学">小学</option>
                            <option value="中学">中学</option>
                            <option value="高中">高中</option>
                            <option value="大专">大专</option>
                            <option value="本科">本科</option>
                            <option value="研究生">研究生</option>
                        </select>
                    </div>
                </div>
                <div class="layui-form-item">
                    <label class="layui-form-label">出生日期</label>
                    <div class="layui-input-block">
                        <input id="select-birthday" type="text" name="birthday" class="layui-input">
                    </div>
                </div>
                <div class="layui-form-item">
                    <label class="layui-form-label">入职时间</label>
                    <div class="layui-input-block">
                        <input id="select-entry-date" type="text" name="entryDate" class="layui-input">
                    </div>
                </div>
                <div class="layui-form-item">
                    <label class="layui-form-label">岗位区域</label>
                    <div class="layui-input-block">
                        <select id="select-area" name="area" lay-filter="type">
                            <option>选择区域</option>
                        </select>
                    </div>
                </div>
                <div class="layui-form-item">
                    <label class="layui-form-label">角色</label>
                    <div id="roles-layer" class="layui-input-block">
                    </div>
                </div>

                <div class="layui-form-item">
                    <button class="layui-btn layui-btn-fluid" lay-submit lay-filter="form-submit">确定
                    </button>
                </div>
            </form>
        </div>
    </div>
</script>
<script type="text/html" id="stateTpl">
    <input type="checkbox" name="state" value="{{d.id}}" lay-skin="switch" lay-text="启用|禁用" lay-filter="changeState"
           {{ d.isEnabled== 1 ? 'checked' : '' }}>
</script>
<script src="/layui/layui.js"></script>
<script src="/layui/layui.all.js"></script>
<script src="/js/jquery.min.js"></script>
<script src="/js/jquery.qrcode.min.js"></script>
<script th:inline="none">
    // layui.use(function () {
    // })


    layui.config({
        base: '/' //静态资源所在路径
    }).extend({
        index: 'lib/index' //主入口模块
    }).use(['index', 'table', 'form', 'upload', 'laydate'], function () {
        var $ = layui.$;
        var table = layui.table;
        var form = layui.form;
        var admin = layui.admin;
        var upload = layui.upload;
        var laydate = layui.laydate
        var popupIndex;
        var userId;

        loadRoles(function (result) {
            for (var i in result) {
                var item = result[i];
                $('#search-role').append('<option value="' + item.id + '">' + item.name + '</option>');
            }
            form.render();
        });

        upload.render({
            elem: '#btn-import',
            url: 'users/import',
            auto: true,
            size: 2048,
            accept: 'file',
            exts: 'xlsx',
            before: function () {
                layer.load();
            },
            done: function (result) {
                layer.closeAll('loading');
                if (result.msg) {
                    layer.alert(result.msg, {
                        area: '800px',
                        skin: 'layui-layer-molv'
                    });
                } else {
                    layer.msg('导入成功');
                }
                search();
            }
        });

        table.render({
            elem: '#user-table',
            url: 'users',
            title: '',
            skin: 'line',
            cols: [[
                {type: 'checkbox'},
                {
                    title: '序号', width: 60, templet: function (d) {
                        return d.LAY_TABLE_INDEX + 1;
                    }
                },
                {field: 'name', title: '姓名'},
                {field: 'code', title: '编码'},
                {field: 'account', title: '账号'},
                {field: 'mobile', title: '手机号'},
                /*{ field: 'gender', title: '性别' },
                { field: 'education', title: '学历' },
                { field: 'age', title: '年龄' },
                { field: 'birthday', title: '出生日期' },*/
                {field: 'area', title: '岗位区域'},
                {field: 'roleNames', title: '角色'},
                {field: 'syncText', title: '同步状态'},
                {field: 'isEnabled', title: '启用状态', width: 150, templet: '#stateTpl'},
                {fixed: 'right', title: '操作', width: 320, align: 'center', toolbar: '#toolbar-operation'}
            ]],
            page: true
        });

        /**
         * 加载角色
         * @param callback
         */
        function loadRoles(callback) {
            $.get('roles', function (result) {
                if (callback) {
                    callback(result.data);
                }
            });
        }

        function loadAreas(callback) {
            $.get('/areas', function (result) {
                if (callback) {
                    callback(result.data);
                }
            });
        }

        function showUserForm(data) {
            loadRoles(function (roles) {
                popupIndex = admin.popupRight({
                    area: '360px',
                    success: function () {
                        var formHtml = $('#user-form').html();
                        $('#' + this.id).html(formHtml);
                        laydate.render({
                            elem: '#select-birthday',
                            type: 'date'
                        });
                        laydate.render({
                            elem: '#select-entry-date',
                            type: 'date'
                        });
                        loadAreas(function (result) {
                            for (var i in result) {
                                var item = result[i];
                                $('#select-area').append('<option value="' + item.name + '">' + item.name + '</option>');
                            }
                            for (let i in roles) {
                                let role = roles[i];
                                $('#roles-layer').append('<input type="checkbox" name="role" lay-skin="primary" value="' + role.id + '" title="' + role.name + '">');
                            }
                            form.render();
                            //监听姓名，自动生成账号
                            $("#name").on("input", function (e) {
                                var text = e.delegateTarget.value;
                                $.post('users/pinyin', {text}, function (result) {
                                    $("#account").val(result.data);
                                });
                            });
                            if (data) {
                                form.val('user-form', data);
                                $("#name").attr("disabled", "disabled");
                                $("#account").attr("disabled", "disabled");
                                let roles = data.roles;
                                if (roles) {
                                    let ids = roles.split(',');
                                    for (let i in ids) {
                                        $('input[name="role"][value="' + ids[i] + '"]').prop("checked", true);
                                    }
                                    form.render();
                                }
                            } else {
                                $("#name").removeAttr("disabled");
                                $("#account").removeAttr("disabled");
                            }
                            form.render();
                        });
                    }
                });
            });
            return popupIndex;
        }

        function closePopupForm() {
            if (popupIndex) {
                layer.close(popupIndex);
            }
        }

        function search() {
            table.reload('user-table', {
                where: {
                    roleId: $('#search-role').val(),
                    keyword: $('#search-keyword').val(),
                },
                page: {
                    curr: 1
                }
            });
        }

        function resetPassword(userId) {
            layer.confirm('真的重置密码吗？', function (index) {
                var url = 'users/' + userId + '/reset-password';
                $.get(url, function (result) {
                    if (result.code == 200) {
                        layer.msg('密码重置成功');
                    } else {
                        layer.msg('密码重置失败');
                    }
                });
                layer.close(index);
            });
        }

        function showQRCode(qrcode) {
            $('#qrcode').empty();
            $('#qrcode').qrcode(qrcode);
            layer.open({
                type: 1,
                shade: false,
                title: false,
                content: $('#qrcode')
            });
        }

        /**
         * 批量同步企微用户
         * @param ids
         */
        function batchSync(ids) {
            $.post('/users/batch-sync-wework', {ids}, function (result) {
                table.reload('user-table');
                if (result.code == 200) {
                    layer.msg('同步成功');
                } else {
                    layer.msg(result.msg);
                }
            });
        }

        $("#btn-search").on('click', function () {
            search();
        })

        $('#keyword').keypress(function (e) {
            if (e.which == 13) {
                search();
            }
        });

        $("#btn-add").on('click', function () {
            popupIndex = showUserForm();
        });

        $("#btn-export").on('click', function () {
            let url = 'users/export?keyword=' + $('#search-keyword').val();
            window.open(url);
        });

        $("#btn-batch-sync").on('click', function () {
            var ids = [];
            var data = table.checkStatus('user-table').data;
            for (let i in data) {
                ids.push(data[i].id);
            }
            batchSync(ids.toString());
            table.reload('user-table');
        });

        $("#btn-refresh").on('click', function () {
            table.reload('user-table');
            layer.msg('表格已刷新');
        });

        $("#btn-batch-delete").on('click', function () {
            layer.confirm('确定要删除吗?', {icon: 3, title: '提示'}, function (index) {
                var ids = [];
                var data = table.checkStatus('user-table').data;
                for (let i in data) {
                    ids.push(data[i].id);
                }
                $.ajax({
                    url: 'users/' + ids.toString(),
                    type: 'DELETE',
                    success: function (result) {
                        if (result.code == 200) {
                            layer.msg('删除成功');
                            table.reload('user-table');
                        } else {
                            layer.msg('删除失败');
                        }
                    }
                });
            });
        });

        table.on('tool(user-table)', function (obj) {
            var data = obj.data;
            userId = data.id;
            if (obj.event === 'del') {
                layer.confirm('真的删除该记录吗？', function (index) {
                    $.ajax({
                        url: 'users/' + data.id,
                        type: 'DELETE',
                        success: function (result) {
                            if (result.code == 200) {
                                layer.msg('删除成功');
                                table.reload('user-table');
                            } else {
                                layer.msg('提交失败:' + result.msg);
                            }
                        }
                    });
                    layer.close(index);
                });
            } else if (obj.event === 'edit') {
                showUserForm(data);
            } else if (obj.event == 'reset') {
                resetPassword(data.id);
            } else if (obj.event == 'qrcode') {
                showQRCode('user:' + data.code);
            } else if (obj.event == 'sync') {
                $.get('/users/' + data.id + '/sync-wework', function (res) {
                    if (res.code == 200) {
                        layer.msg('同步成功');
                    } else {
                        layer.alert(res.msg);
                        table.reload('user-table');
                    }
                });
            }
        });

        form.on('submit(form-submit)', function (data) {
            var postData = data.field;
            var ids = [];
            var roles = "";
            $('input[name="role"]:checked').each(function (index, item) {
                ids.push($(this).val());
            });
            for (var i in ids) {
                roles += ids[i] + ",";
            }
            if (roles.length > 0) {
                roles = roles.substring(0, roles.length - 1)
            }
            postData.roles = roles;
            $.ajax({
                url: 'users',
                type: 'PUT',
                data: postData,
                success: function (result) {
                    if (result.code == 200) {
                        layer.msg('操作成功');
                        table.reload('user-table');
                    } else {
                        layer.msg(result.msg);
                        table.reload('user-table');
                    }
                }
            });
            closePopupForm();
            return false;
        });

        form.on('switch(changeState)', function (obj) {
            $.get('users/' + obj.value + '/toggle-state', function (result) {
                if (result.code != 200) {
                    layer.msg('修改状态失败');
                }
            });
        });
    });
</script>
</body>
<div style="display: none;padding: 20px;" id="qrcode"></div>

</html>